package Medium;


public class LC2095 {
    class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    /**
     * 简单解法
     */
    public ListNode deleteMiddle(ListNode head) {
        int N = 0;
        ListNode ptr = head;
        while (ptr != null) {
            N++;
            ptr = ptr.next;
        }

        int i = 0;
        ptr = head;
        ListNode left = null;
        while (i < N / 2) {
            i++;
            left = ptr;
            ptr = ptr.next;
        } // 循环结束后，ptr指向待删除的结点，left指向ptr前一个结点
        if (left == null) return null;
        left.next = ptr.next;
        return head;
    }

    /**
     * 快慢指针解法。快指针一次前进2位，慢指针一次前进1位；当快指针达到链表末尾时，慢指针指向需要被删除的元素。
     */
    public ListNode fastAndSlow(ListNode head) {
        ListNode fast = head, slow = head;
        ListNode left = null;
        while (true) {
            if (fast != null && fast.next != null) {
                fast = fast.next.next;
                left = slow;
                slow = slow.next;
            }
            else { // fast指向最后一个元素，或已经指向空元素，此时slow指向的就是需要删除的元素
                if (left == null) return null;
                left.next = slow.next;
                return head;
            }
        }
    }
}
